from jwt import ExpiredSignatureError, InvalidTokenError
import jwt
from datetime import datetime, timedelta

SECRET_KEY = "djangobase+vue"


def decode_jwt(token):
    try:
        # 解码 token，自动验证过期时间和签名
        decoded_payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        username = decoded_payload.get("username")
        return username
    except ExpiredSignatureError:
        print("Token has expired.")
        return None
    except InvalidTokenError:
        print("Invalid token.")
        return None


def generate_jwt(username):
    payload = {
        "username": username,
        "exp": datetime.utcnow() + timedelta(hours=1)  # 有效期1小时
    }
    # 直接返回字符串类型的 token
    token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
    return token  # 不需要 decode


if __name__ == "__main__":
    # 生成 token
    username = "example_user"
    token = generate_jwt(username)
    print(f"Generated Token: {token}")

    # 解码 token
    decoded_username = decode_jwt(token)
    print(f"Decoded Username: {decoded_username}")
